package org.jash.user.register

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.common.mvi.NetworkResult
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class RegisterViewModel(private val repository: RegisterRepository) : BaseViewModel<RegisterIntent, RegisterViewState, RegisterViewState>() {
    override fun initialState(): RegisterViewState = RegisterViewState()

    override suspend fun handleIntent(intent: RegisterIntent) {
        when (intent) {
            is RegisterIntent.Register -> register(intent.username, intent.password)
        }
    }

    private suspend fun register(username: String, password: String) {
        updateState(currentState().copy(isLoading = true, error = null, isSuccess = false))
        repository.register(username, password).collect { result ->
            when (result) {
                is NetworkResult.Loading -> updateState(currentState().copy(isLoading = true, error = null))
                is NetworkResult.Success -> updateState(currentState().copy(isLoading = false, isSuccess = true, error = null))
                is NetworkResult.Error -> updateState(currentState().copy(isLoading = false, isSuccess = false, error = result.exception.message))
            }
        }
    }
}
